//
//  DatePickerController.swift
//  SitPosition
//
//  Created by apple on 2019/2/6.
//  Copyright © 2019 apple. All rights reserved.
//

import Foundation
import UIKit
import Cartography


/**
 * 单选列表值选择器
 */
class DatePickerController : UIViewController {
    
    // MARK: - Properties
    
    // 拿到值时的处理回调
    // value: 选中的值
    public var onGotValue: (_ value: Date?) -> Void = { _ in }
    
    // 选中的时间
    public var selectedDate: Date? = nil
    
    // 面板
    private var panel: UIView = UIView.colored(UIColor.white)
    
    // Picker
    private lazy var picker: UIDatePicker = {
        let view = UIDatePicker()
        view.locale = Locale(identifier: "zh")
        view.datePickerMode = .date
        view.setDate(Date(), animated: false)
        view.maximumDate = Date()
        view.addTarget(self, action: #selector(_handleDatePickerValueChanged(_:)),
                       for: UIControl.Event.valueChanged)
        return view
    }()
    
    // 确定、取消按钮
    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.lighgrayTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        btn.addTarget(self, action: #selector(_handleCancel), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.cancel, for: UIControl.State.normal)
        return btn
    }()
    
    private let horSeperator: UIView = UIView.colored(Theme.Color.seperatorColor)
    private let verSeperator: UIView = UIView.colored(Theme.Color.seperatorColor)
    
    private lazy var okBtn: UIButton = {
        let btn = UIButton(type: UIButton.ButtonType.custom)
        btn.setTitleColor(Theme.Color.primaryBlueTextColor, for: UIControl.State.normal)
        btn.titleLabel?.font = Theme.Font.regularFont(ofSize: 16)
        btn.addTarget(self, action: #selector(_handleOk), for: UIControl.Event.touchUpInside)
        btn.setTitle(Strings.ok, for: UIControl.State.normal)
        return btn
    }()
    
    // MARK: - Object lifecycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        
        // 子视图
        panel.addSubviews([picker, horSeperator, cancelBtn, verSeperator, okBtn])
        view.addSubview(panel)
        _setupConstraints()
        
        // 手势
        let tapableView: UIView = {
            let view = UIView()
            view.backgroundColor = UIColor.clear
            return view
        }()
        view.insertSubview(tapableView, at: 0)
        constrain(tapableView, view) { v, parent in
            v.edges == parent.edges
        }
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(_handleCancel))
        tapableView.addGestureRecognizer(tapGesture)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 动效
        panel.transform = CGAffineTransform.init(translationX: 0, y: 275)
        UIView.animate(withDuration: 0.35, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity:0.5, options: UIView.AnimationOptions.preferredFramesPerSecond60, animations: { [weak self] in
            self?.panel.transform = .identity
            }, completion: nil)
    }
    
    // MARK: - Private Methods
    
    // 取消
    @objc func _handleCancel() {
        onGotValue(nil)
    }
    
    // 确定
    @objc func _handleOk() {
        onGotValue(selectedDate ?? Date())
    }
    
    // 设置视图约束
    func _setupConstraints() {
        let pickerH: CGFloat = 191
        let buttonH: CGFloat = 50
        
        // panel
        constrain(panel, view) { v, parent in
            let height: CGFloat = pickerH+buttonH
            v.bottom == parent.bottom
            v.left == parent.left
            v.right == parent.right
            if #available(iOS 11.0, *) {
                v.top == parent.safeAreaLayoutGuide.bottom - height
            } else {
                v.height == height
            }
        }
        
        // picker
        constrain(picker, panel) { v, parent in
            v.top == parent.top
            v.left == parent.left
            v.right == parent.right
            v.height == pickerH
        }
        
        constrain(horSeperator, picker, panel) { v, sibling, parent in
            v.top == sibling.bottom
            v.left == parent.left
            v.right == parent.right
            v.height == 1
        }
        
        // button(s)
        constrain(cancelBtn, horSeperator, panel) { v, sibling, parent in
            v.top == sibling.bottom
            v.left == parent.left
            v.width == parent.width / 2 - 0.5
            v.height == buttonH-1
        }
        
        constrain(verSeperator, cancelBtn, panel) { v, sibling, parent in
            v.top == sibling.top
            v.centerX == parent.centerX
            v.width == 1
            v.bottom == parent.bottom
        }
        
        constrain(okBtn, cancelBtn, panel) { v, sibling, parent in
            v.top == sibling.top
            v.right == parent.right
            v.width == sibling.width
            v.height == sibling.height
        }
    }
    
    @objc func _handleDatePickerValueChanged(_ sender: Any) -> Void {
        selectedDate = picker.date
    }
}
